from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext
from django import forms

import traceback

from kz.edu.sdu.itech.pcs import mclient as m
from kz.edu.sdu.itech.pcs.common import Alphabet, ServerStatus 

from django.template.loader import render_to_string
from django.core import servers


DEBUG = True

def trace(fun):
    def new_fun(*args, **kwargs):
        try:
            return fun(*args, **kwargs)
        except:
            if DEBUG: traceback.print_exc()
        return False
    return new_fun

class ServerWrapper(object):
    server = None
    
    @trace
    def __init__(self):
        monitor = m.Monitor()
        self.server = m.Server(monitor)            

    @trace
    def refresh_status(self):
        self.server.refresh()

    @trace
    def load_workers(self):
        self.server.loadWorkers()
                
    @trace
    def get_status(self):
        res = self.refresh_status()
        if res == False:
            return ServerStatus.OFFLINE
        return self.server.getStatus()
    
    @trace
    def get_workers(self):        
        res = self.load_workers()
        if res == False:
            return None
        map = self.server.getWorkers()
        dict = {}
        for key in map.keySet():
            value = map.get(key)
            t = value.split('|')
            dict.update({key: (t[0],t[1])})
        return dict
            
    @trace
    def setup_work(self):
        if not (self.server.getStatus() == ServerStatus.RUNNING):
            self.server.setupWork()
        else:
            print 'server is running'
    
    @trace
    def setJob(self, alphabet, length, hash):
        self.server.setAlphabet(alphabet)
        self.server.setLen(length)
        self.server.setHash(hash)
        res = self.setup_work()
    
    @trace
    def start(self):
        if self.server.getStatus() == ServerStatus.INSTALLED:
            self.server.startWork()
        else:
            print 'job is not installed'
            
    @trace
    def load_job(self):
        self.server.loadJob()
        
    def get_job_data(self):
        res = self.load_job()
        if res:
            return None
        data = {
            'alphabet' : self.server.getAlphabet().toString(),
            'len': self.server.getLen(),
            'hash': self.server.getHash(),
        }        
        return data

    @trace
    def stop(self):
        if self.server.getStatus() == ServerStatus.RUNNING:
            self.server.stopWork()
        else:
            print 'job is not running'
        

        
class JobForm(forms.Form):
    alphabet = forms.CharField(help_text='ex:a-z,123wedsa')
    length   = forms.IntegerField()
    hash     = forms.IntegerField()
    

def index(request, template_name="first.html"):
#    server = cache.get('server')
#    if server is None:
    server = ServerWrapper()

    form = JobForm(initial=server.get_job_data())
    if request.method == "POST":
        form = JobForm(request.POST)
        if form.is_valid():
            t = form.cleaned_data.get('alphabet','').split(',')
            a = Alphabet()
            for x in t:
                a.add(x)
            l = form.cleaned_data.get('length',0)
            h = form.cleaned_data.get('hash',0)
            server.setJob(a, l, h)
#            server.start()
            return HttpResponseRedirect('/')
            
    c = RequestContext(request, {'server': server, 'form': form })    
    result = render_to_string(template_name, c)
#    cache.set('server', server)
    return HttpResponse(result)
